<template>
  <div>
    <c-slot :isNeedConfig="true" class="m-slot no-margin">
      <template slot="title">{{ tname }}</template>
      <template slot="config">
        <ChooseScreen
          :selectATit="selectATit"
          :param="param"
          :tname="tname"
          :leftTreeParentId="leftTreeParentId"
          :searchWord="searchWord"
          @getChartData="getChartData"
        ></ChooseScreen>
      </template>
      <template slot="chart">
        <ChartA
          v-if="datatype !== -1"
          :chartId="chartId"
          :chartData="chartData"
          @chartDom="chartDom"
          @domRef="getDomRef"
        />
        <div v-if="loading" class="chart-loading-box">
          <loading1 :emptyText="emptyText" />
        </div>
      </template>
      <template slot="type">
        <i class="icon el-icon-download" @click="exportData">导出数据</i>
        <i class="icon el-icon-download" @click="downloadImg">保存图片</i>
        <i class="icon el-icon-full-screen" @click="handleFullScreen">&nbsp;全屏</i>
      </template>
    </c-slot>
    <!-- 表格 -->
    <div id="chart-tab" class="chart-tab">
      <ul class="chart-tab-ul">
        <li class="tit">
          <p v-for="(item, index) in tableData.tit" :key="index">{{ item }}</p>
        </li>
        <li
          v-for="(item, index) in tableData.content"
          :key="index"
          class="content"
        >
          <p>{{ index + 1 }}</p>
          <p v-for="(ite, j) in item" :key="j">{{ ite }}</p>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import { mapState } from "vuex";
import CSlot from "@/views/modules/Analysis/CSlot";
import ChartA from "../charts/ChartA";
import {
  refactor,
  getYear,
  transCNCountry,
  downloadChartImg
} from "@/utils/utils";
import base64 from "@/utils/base64.js";
import ChooseScreen from "./chooseScreen.vue";
import mixin from "@/mixins/expert";

export default {
  mixins: [mixin],
  props: {
    chartTempl: {
      type: Object
    },
    dcData: {
      type: Object
    }
  },
  components: {
    CSlot,
    ChartA,
    ChooseScreen
  },
  data() {
    return {
      searchTxt: "",
      loading: true,
      cancel: null,
      tname: "", // 标题
      param: {}, // 图表参数
      selectATit: "", // 筛选条件A，动态
      timeType: "isd", // 设置时间筛选类型
      chartId: "", // 图表id名称,
      datatype: -1, // 图表数据类型
      //
      chartData: [],
      dom: {},
      domRef: null, // 记录图表dom对象，用于全屏
      dbid: "",
      tableData: {
        tit: [],
        content: []
      },
      yearArr: [],
      emptyText: "数据加载中...",
      timeType: "",
      datefieldformat: "", //0: yyyy  1: yyyy-mm-dd  2: yyyy-mm-dd hh:mm:ss
      datefieldformatTxt: "",
      leftTreeParentId: 0
    };
  },
  computed: {
    ...mapState(["searchWord"])
  },
  watch: {
    // chartTempl: {
    //   handler: function(newData, oldData) {
    //     if (oldData.id !== newData.id) {
    //       this.init();
    //     }
    //   }
    // },
    dcData() {
      this.init();
    }
  },
  mounted() {
    this.dbid = String(this.$route.query.type);
    // this.init();
  },
  methods: {
    init() {
      this.leftTreeParentId = this.chartTempl.parentId;
      this.tname = this.chartTempl.tname;
      this.param = this.chartTempl.tdata.param;
      this.chartId = "chart" + this.chartTempl.id;
      this.datatype = this.chartTempl.tdata.datatype;
      this.timeType = this.chartTempl.tdata.datefield;
      this.datefieldformat = this.chartTempl.tdata.datefieldformat;
      this.datefieldformatTxt = this.datefieldformat == 1 ? "-01-01" : "";
      if (this.dcData && this.dcData.chartData) {
        let data = JSON.parse(JSON.stringify(this.dcData.chartData));
        this.loading = false;
        data.forEach(v => {
          v.key = transCNCountry(v.key);
        });
        refactor({
          type: this.dcData.datatype, // 根据后台返回的datatype，判断数据解析格式
          data,
          callback: refactor => {
            this.chartData = refactor.data;
            // 处理表格
            let yearArr = []
            refactor.yearArr.forEach(v => {
              yearArr.push(moment(v).format("YYYY"))
            })
            this.tableData.tit = [
              "",
              "",
              ...yearArr
            ]
            this.tableData.content = refactor.dataArr
          }
        });
      } else {
        this.emptyText = "暂无数据";
      }
    },
    getChartData(Params) {
      if (this.cancel !== null) {
        this.cancel();
      }
      this.searchTxt = this.$route.query.keyword || this.searchWord;
      let sq = `${this.timeType}>=${Params.startYear}${this.datefieldformatTxt} AND ${this.timeType}<=${Params.endYear}${this.datefieldformatTxt}`;
      if (this.searchTxt !== "") {
        sq = `${this.searchTxt} AND ` + sq;
      }
      this.loading = true;
      this.emptyText = "数据加载中...";
      this.chartData = [];
      this.tableData = {
        tit: [],
        content: []
      };
      //触发search接口
      let waggs = this.chartTempl.tdata.param.aggs;
      waggs[0]["size"] = Params.size;
      if (waggs[0]["aggs"]) {
        waggs[0]["aggs"][0]["size"] = Params.size;
      }
      let params = {
        aggs: this.chartTempl.tdata.param.aggs,
        dbid: this.dbid,
        eSearch: sq,
        ipi: 1,
        ips: 0,
        rSearch: "",
        smartSearch: "",
        sort: []
      };
      let subjects = this.$route.query.subjects;
      if (subjects) {
        params["subjects"] = base64.decode(subjects);
      }
      let familyFlag = localStorage.getItem("familyFlag") || false;
      if (familyFlag ==1 ) {
        params["familyFlag"] = true; // 同族合并
        params["tzzlhb"] = false; // 同专利合并
      } else if (familyFlag ==2) {
        params["familyFlag"] = false; // 同族合并
        params["tzzlhb"] = true; // 同专利合并
      }
      let ths = this;
      this.$post(this.$Url.search.commonSearch, params, {
        cancelToken: new axios.CancelToken(function executor(c) {
          ths.cancel = c;
        })
      })
        .then(res => {
          let data = JSON.parse(JSON.stringify(res.data.chartData));

          this.$store.commit("setTotalTxt", res.data.total);
          this.loading = false;
          data.forEach(v => {
            v.key = transCNCountry(v.key);
          });
          refactor({
            type: 0, // 根据后台返回的datatype，判断数据解析格式
            data,
            callback: refactor => {
              this.chartData = refactor.data;
              // 处理表格
              let yearArr = []
              refactor.yearArr.forEach(v => {
                yearArr.push(moment(v).format("YYYY"))
              })
              this.tableData.tit = [
                "",
                "",
                ...yearArr
              ]
              this.tableData.content = refactor.dataArr
            }
          });
        })
        .catch(err => {
          this.emptyText = "暂无数据";
          this.loading = false;
        });
    },
    getDomRef(dom) {
      this.domRef = dom
    },
    chartDom(dom) {
      this.dom = dom;
      this.analysisExport();
    },
    // 全屏
    handleFullScreen() {
      let element = this.domRef
      if (!element) {
        return
      }
      // 全屏查看
      if (element.requestFullScreen) {
        // HTML W3C 提议
        element.requestFullScreen();
      } else if (element.msRequestFullscreen) {
        // IE11
        element.msRequestFullScreen();
      } else if (element.webkitRequestFullScreen) {
        // Webkit
        element.webkitRequestFullScreen();
      } else if (element.mozRequestFullScreen) {
        // Firefox
        element.mozRequestFullScreen();
      }
      // 退出全屏
      if (element.requestFullScreen) {
        document.exitFullscreen();
      } else if (element.msRequestFullScreen) {
        document.msExitFullscreen();
      } else if (element.webkitRequestFullScreen) {
        document.webkitCancelFullScreen();
      } else if (element.mozRequestFullScreen) {
        document.mozCancelFullScreen();
      }
    },
    // 保存图片
    downloadImg() {
      downloadChartImg(this.dom);
    },
    // 导出数据
    exportData() {
      let aoa = [];
      let content = [];
      this.tableData.content.forEach((v, i) => {
        content.push([i, ...v]);
      });
      aoa = [this.tableData.tit, ...content];
      var ws = XLSX.utils.aoa_to_sheet(
        aoa
      ); /* 新建空workbook，然后加入worksheet */
      var wb = XLSX.utils.book_new(); /*新建book*/
      XLSX.utils.book_append_sheet(
        wb,
        ws,
        name
      ); /* 生成xlsx文件(book,sheet数据,sheet命名) */
      XLSX.writeFile(wb, `${this.tname}.xlsx`);
    }
  },

  beforeDestroy() {
    if (this.cancel !== null) {
      this.loading = false;
      this.cancel();
    }
  }
};
</script>

<style lang="scss"></style>
